module.exports = function ($resource, $state, $http, $q, $modal, dlq, $timeout) {
	return {
		restrict: 'AE',
		template: require('../views/p_model.html'),
		replace: true,
		scope: {
			'p' : '=',
			'load': '=',
			//'state' : '=',
			//'vm' : '=',
		},
		link: function (scope, elements, attrs) {

	scope.m = {
		'sale_code' : scope.p.sale_code,
    	'attr_name' : '',
    	'guide_price': 0,
    	'cost_price' : 0,
    	'stock_type' : '0',
    	'current_stock_num' : 0,
    	'order_num_state' : '0',
    	'order_limit_num' : 1,
    	'order_limit_type' : '0',
    };


	scope.addModel = function(){

		if(scope.m.attr_name == ''){
			alert('请填写型号名');
			return;
		}
		
		optTicket(scope.m);

	}


	scope.saveModel = function(obj){
		if(obj.attr_name == ''){
			alert('请填写型号名');
			return;
		}

		if(obj.guide_price <= 0){
			alert('请输入正确价格');
			return;
		}

		optTicket(obj);
	};


	scope.setAttrName = function(obj){

		var para = {
			'id' : obj.attr_id,
			'sale_code' : obj.sale_code, 
			'attr_name' : obj.attr_name,
		}
		optTicket(para, function(){
			obj.opt.attr_name = obj.opt.attr_name == '0' ? '1' : '0';
		});

	};

	
	scope.setGuidePrice = function(obj){

		var para = {
			'id' : obj.attr_id,
			'sale_code' : obj.sale_code, 
			'guide_price' : obj.guide_price,
		}
		optTicket(para, function(){
			obj.opt.guide_price = obj.opt.guide_price == '0' ? '1' : '0';
		});

	};

	
	scope.setCostPrice = function(obj){

		var para = {
			'id' : obj.attr_id,
			'sale_code' : obj.sale_code, 
			'cost_price' : obj.cost_price,
		}
		optTicket(para, function(){
			obj.opt.cost_price = obj.opt.cost_price == '0' ? '1' : '0';
		});

	};

	
	scope.setStock = function(obj){

		var para = {
			'id' : obj.attr_id,
			'sale_code' : obj.sale_code, 
			'stock_type' : obj.stock_type,
			'current_stock_num' : obj.current_stock_num,
		}
		optTicket(para, function(){
			obj.opt.stock = obj.opt.stock == '0' ? '1' : '0';
		});

	};


	scope.up = function(obj){

		var para = {
			'id' : obj.attr_id,
			'sale_code' : obj.sale_code, 
			'state' : '1',
		}
		optTicket(para, function(){
			scope.load();
		});
	};

	scope.down = function(obj){

		var para = {
			'id' : obj.attr_id,
			'sale_code' : obj.sale_code, 
			'state' : '0',
		}
		optTicket(para, function(){
			scope.load();
		});
	};



	scope.changeOpt = function(obj, para){
		obj.opt[para] = obj.opt[para] == '0' ? '1' : '0';
	};


	function optTicket(para, fun){

		$resource('/api/ac/wc/newProductService/createAttr', {}, {}).save(para, function(res){
			console.log(res);
			if (res.errcode !== 0) {
				alert(res.errmsg);
				return;
			}
			scope.load();
			if(angular.isDefined(fun)){
				fun();
			}
		});
	}


	scope.cancel = function(){

		scope.close();

	}

		

		}
	};
};

